package com.zzyl.service.impl;

import cn.hutool.json.JSONObject;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.service.MemberService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.WechatUtil;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private WechatUtil wechatUtil;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 客户登录
     *
     * @param userLoginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //1.获取openid
        String openid = wechatUtil.getOpenid(userLoginRequestDto.getCode());

        //2.根据openid查询用户
        Member member = memberMapper.showMemberByOpenid(openid);
        //2.1判断用户是否为空
        if (ObjectUtil.isEmpty(member)) {
            //为空创建对象
            member = new Member();
            member.setOpenId(openid);
            member.setName(userLoginRequestDto.getNickName());
        }

        //3.获取接口调用凭证
        String token = wechatUtil.getToken();
        //4.获取用户手机号
        String phone = wechatUtil.getPhone(token, userLoginRequestDto.getPhoneCode());

        //判断查询的客户手机号是否存在
        if (ObjectUtil.isEmpty(member.getPhone())) {
            //不存在新用户，插入数据库
            member.setPhone(phone);
            memberMapper.insertMember(member);
        }

        //判断手机号是否变更
        if (!ObjectUtil.equals(member.getPhone(), phone)) {
            //变更修改手机号
            memberMapper.updatePhoneByOpenId(phone, openid);
        }

        //用户存在生成jwt令牌
        HashMap<String, Object> memberMap = new HashMap<>();
        memberMap.put("userId", member.getId());
        String jwt = jwtUtil.createJWT(memberMap);

        //创建LoginVo对象封装jwt并返回
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(jwt);
        loginVo.setNickName(member.getName());
        return loginVo;
    }
}
